package com.uduemc.biso.node.web.component.html;

import java.io.IOException;
import java.io.StringWriter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.core.common.sysconfig.ArticleSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.articlesysconfig.ArticleSysItemConfig;
import com.uduemc.biso.node.core.common.sysconfig.articlesysconfig.ArticleSysItemTextConfig;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SArticle;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SSystemItemCustomLink;
import com.uduemc.biso.node.core.entities.custom.Article;
import com.uduemc.biso.node.core.entities.custom.CategoryQuote;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.SArticlePrevNext;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.SpringContextUtils;
import com.uduemc.biso.node.web.service.byfeign.SystemService;
import com.uduemc.biso.node.web.utils.IconClassUtil;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

@Component
public class HSystemArticleItemUdin {

	private static String name = "system_article_item";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

//	@Autowired
//	private SiteUrlComponent siteUrlComponent;

	public StringBuilder html(SPage sPage, ArticleSysConfig articleSysConfig, Article article, SArticlePrevNext sArticlePrevNext) {
		if (articleSysConfig == null) {
			return new StringBuilder("<!-- articleSysConfig empty -->");
		}
		// 生成html渲染内容
		StringBuilder stringBuilder = new StringBuilder("<!-- article item page -->\n");
		ArticleSysItemConfig articleSysItemConfig = articleSysConfig.getItem();
		ArticleSysItemTextConfig articleSysItemTextConfig = articleSysConfig.getItext();
		if (null == article || null == article.getSArticle() || article.getSArticle().getIsRefuse() == (short) 1) {
			// 没有数据
			Map<String, Object> mapData = new HashMap<>();
			mapData.put("noData", articleSysItemTextConfig.getNoData());
			StringWriter render = basicUdin.render(name, "nodata", mapData);
			stringBuilder.append(render);
			return stringBuilder;
		}
		SArticle sArticle = article.getSArticle();

		// 栏目
		CategoryQuote categoryQuote = article.getCategoryQuote();
		String column = articleSysItemTextConfig.getColumn();
		String categoryName = "";
		if (categoryQuote != null) {
			SCategories sCategories = categoryQuote.getSCategories();
			if (sCategories != null) {
				categoryName = sCategories.getName();
			}
		}

//		System.out.println(article.getFileList());
		List<RepertoryQuote> fileList = article.getFileList();
		String fileListHtml = "";
		if (CollUtil.isNotEmpty(fileList)) {
			fileListHtml = makeFileListHtml(articleSysItemTextConfig, fileList);
		}

		// 发布时间
		String releaseTime = articleSysItemTextConfig.getReleaseTime();
		String timeFormat = articleSysItemConfig.getTimeFormat();
		if (StringUtils.isEmpty(timeFormat)) {
			timeFormat = "yyyy-MM-dd HH:mm:ss";
		}
		Date releasedAt = sArticle.getReleasedAt();
		String relTime = "";
		if (releasedAt != null) {
			Instant instant = releasedAt.toInstant();
			LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

			DateTimeFormatter ofPatternTime = DateTimeFormatter.ofPattern(timeFormat);
			// DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			relTime = localDateTime.format(ofPatternTime);
		}

		// 是否显示作者
		int isShowAuthor = articleSysItemConfig.getIsShowAuthor();
		String authort = HtmlUtils.htmlEscape(articleSysItemTextConfig.getAuthort());

		// 是否显示来源
		int isShowOrigin = articleSysItemConfig.getIsShowOrigin();
		String origint = HtmlUtils.htmlEscape(articleSysItemTextConfig.getOrigint());

		// 返回按钮
		int isShowBackBtn = articleSysItemConfig.getIsShowBackBtn();
		String returnt = HtmlUtils.htmlEscape(articleSysItemTextConfig.getReturnt());

		// 是否显示分享
		int isShare = articleSysItemConfig.getIsShare();
		String shareadt = HtmlUtils.htmlEscape(articleSysItemTextConfig.getShareadt());

		// 是否显示浏览总数
		int isViewCount = articleSysItemConfig.getIsViewCount();
		String browseVolume = HtmlUtils.htmlEscape(articleSysItemTextConfig.getBrowseVolume());

		int prevNext = articleSysItemConfig.getShowPrevNext();
		String prevNextHtml = prevNext == 1 ? makePrevNextHtml(sPage, articleSysItemTextConfig, sArticlePrevNext) : "";

		htmlEscape(sArticle);
		Map<String, Object> mapData = new HashMap<>();
		mapData.put("sArticle", sArticle);
		mapData.put("column", column);
		mapData.put("categoryName", categoryName);
		mapData.put("releaseTime", releaseTime);
		mapData.put("relTime", relTime);
		mapData.put("isShowAuthor", isShowAuthor);
		mapData.put("authort", authort);
		mapData.put("isShowOrigin", isShowOrigin);
		mapData.put("origint", origint);
		mapData.put("isShowBackBtn", isShowBackBtn);
		mapData.put("returnt", returnt);
		mapData.put("isShare", isShare);
		mapData.put("shareadt", shareadt);
		mapData.put("isViewCount", isViewCount);
		mapData.put("browseVolume", browseVolume);
		mapData.put("fileListHtml", fileListHtml);
		mapData.put("prevNextHtml", prevNextHtml);
		StringWriter render = basicUdin.render(name, "default", mapData);
		stringBuilder.append(render);
		return stringBuilder;
	}

	protected void htmlEscape(SArticle sArticle) {
		String author = sArticle.getAuthor() != null ? HtmlUtils.htmlEscape(sArticle.getAuthor()) : "";
		String title = sArticle.getTitle() != null ? HtmlUtils.htmlEscape(sArticle.getTitle()) : "";
		String origin = sArticle.getOrigin() != null ? HtmlUtils.htmlEscape(sArticle.getOrigin()) : "";
		String content = sArticle.getContent() != null ? sArticle.getContent() : "";
		sArticle.setAuthor(author).setTitle(title).setOrigin(origin).setContent(content);
	}

	protected String makeFileListHtml(ArticleSysItemTextConfig articleSysItemTextConfig, List<RepertoryQuote> fileList) {
		if (CollUtil.isEmpty(fileList)) {
			return "";
		}

		// 是否需要身份授权后才能进行下载
		boolean identity = false;

		List<Map<String, String>> fileListMap = new ArrayList<>();
		for (RepertoryQuote repertoryQuote : fileList) {
			HRepertory hRepertory = repertoryQuote.getHRepertory();

			Map<String, String> downFile = new HashMap<>();
			String filename = repertoryQuote.getHRepertory().getOriginalFilename();
			String downloadhref = identity ? "javascript:void(0);" : siteUrlComponent.getDownloadHref(hRepertory.getId());
			String icon = IconClassUtil.systemItemDownload(hRepertory.getSuffix());

			String token = String.valueOf(hRepertory.getId());
			try {
				token = CryptoJava.en(token);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String onlineBrowseHref = "javascript:void(0);";
			String suffix = hRepertory.getSuffix();
			if (StrUtil.isNotBlank(suffix) && suffix.toLowerCase().equals("pdf")) {
				suffix = suffix.toLowerCase();
				onlineBrowseHref = siteUrlComponent.getPreviewPdfHref(filename, hRepertory.getId());
			}

			downFile.put("icon", icon);
			downFile.put("token", token);
			downFile.put("filename", filename);
			downFile.put("suffix", suffix);
			downFile.put("onlineBrowseHref", onlineBrowseHref);
			downFile.put("downloadhref", downloadhref);
			fileListMap.add(downFile);
		}

		String downText = articleSysItemTextConfig.getDownText();
		downText = StrUtil.isNotBlank(downText) ? HtmlUtils.htmlEscape(downText) : "";

		String onlineBrowseText = articleSysItemTextConfig.getOnlineBrowseText();
		onlineBrowseText = StrUtil.isNotBlank(onlineBrowseText) ? HtmlUtils.htmlEscape(onlineBrowseText) : "";

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("onlineBrowseText", onlineBrowseText);
		mapData.put("downText", downText);
		mapData.put("fileList", fileListMap);
		StringWriter render = basicUdin.render(name, "file/default", mapData);
		return render.toString();
	}

	protected String makePrevNextHtml(SPage sPage, ArticleSysItemTextConfig articleSysItemTextConfig, SArticlePrevNext sArticlePrevNext) {

		String prevNextNoData = articleSysItemTextConfig.getPrevNextNoData();
		String prevText = articleSysItemTextConfig.getPrevText();
		String nextText = articleSysItemTextConfig.getNextText();

		prevNextNoData = StrUtil.isNotBlank(prevNextNoData) ? HtmlUtils.htmlEscape(prevNextNoData) : "";
		prevText = StrUtil.isNotBlank(prevText) ? HtmlUtils.htmlEscape(prevText) : "";
		nextText = StrUtil.isNotBlank(nextText) ? HtmlUtils.htmlEscape(nextText) : "";

		SArticle prev = sArticlePrevNext != null ? sArticlePrevNext.getPrev() : null;
		SArticle next = sArticlePrevNext != null ? sArticlePrevNext.getNext() : null;

		String prevContent = "";
		if (prev == null) {
			prevContent = prevNextNoData;
		} else {
			String title = HtmlUtils.htmlEscape(prev.getTitle());
			SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
			SSystemItemCustomLink sSystemItemCustomLink = null;
			try {
				sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(prev.getHostId(), prev.getSiteId(), prev.getSystemId(), prev.getId());
			} catch (IOException e) {
			}

			String articleHref = siteUrlComponent.getArticleHref(sPage, prev, sSystemItemCustomLink);
			prevContent = "<a href=\"" + articleHref + "\" title=\"" + title + "\">" + title + "</a>";
		}

		String nextContent = "";
		if (next == null) {
			nextContent = prevNextNoData;
		} else {
			String title = HtmlUtils.htmlEscape(next.getTitle());
			SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
			SSystemItemCustomLink sSystemItemCustomLink = null;
			try {
				sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(next.getHostId(), next.getSiteId(), next.getSystemId(), next.getId());
			} catch (IOException e) {
			}
			String articleHref = siteUrlComponent.getArticleHref(sPage, next, sSystemItemCustomLink);
			nextContent = "<a href=\"" + articleHref + "\" title=\"" + title + "\">" + title + "</a>";
		}

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("prevText", prevText);
		mapData.put("nextText", nextText);
		mapData.put("prevContent", prevContent);
		mapData.put("nextContent", nextContent);
		StringWriter render = basicUdin.render(name, "prevnext", mapData);
		return render.toString();
	}

}
